package leetcode.f1t100;

import java.util.Stack;

/**
 * 校验括号是否闭合
 * https://leetcode.com/problems/valid-parentheses/
 *
 * @Author lichongxiao
 * @Date 2022/9/30 10:08
 */
public class Q20_ValidParentheses {
    public static void main(String[] args) {
        String s = "{}{}{()[]}((";
        System.out.println(new Q20_ValidParentheses().isValid(s));
    }

    public boolean isValid(String s) {
        char[] chars = s.toCharArray();
        Stack<Character> stack = new Stack<>();
        for (int i = 0, length = chars.length; i < length; i++) {
            if(isLeft(chars[i])){
                stack.push(chars[i]);
            }else{
                if(stack.isEmpty() || !isMatch(stack.pop(), chars[i])){
                    return false;
                }
            }
        }
        return stack.isEmpty();
    }

    private boolean isLeft(char c) {
        return c == '(' || c == '[' || c == '{';
    }
    private boolean isMatch(char a,char b){
        return (a == '(' && b == ')') || (a == '[' && b == ']') || (a == '{' && b == '}');
    }
}
